﻿/*-------------------------------------------------------------------------
* 命名空间: XrayDirection.Common/ReqeustHelper 
* 类   名: ReqeustHelper
* 功   能: N/A
* 时   间: 2024-08-28 17:35:16
* 版   本: V1.0
* 作   者: Fioman
* 格   言: Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Prism.Ioc;
using SiliconSelect.Common;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using XrayDirection.Common.EnumVal;
using XrayDirection.HelperManager;
using XrayDirection.ViewModels;

namespace XrayDirection.Common
{
    public class RequestHelper
    {

        private static readonly HttpClient httpClient = new HttpClient();
        private static readonly int _timeOut = 2000;
        private static IContainerProvider _containerProvider;

        public static void SetContainerProvider(IContainerProvider containerProvider)
        {
            _containerProvider = containerProvider;
        }

        public static string GetUuid()
        {
            return Guid.NewGuid().ToString();
        }

        private static void UpdateMsgResponse(string result, string rtnCode, string rtnMsg)
        {
            Application.Current?.Dispatcher?.Invoke(() =>
            {
                _containerProvider.Resolve<EapViewModel>().RequestResponse = result;
                _containerProvider.Resolve<EapViewModel>().ResponseStatus = rtnCode;
                _containerProvider.Resolve<EapViewModel>().ResponseMsg = rtnMsg;
            });
        }

        private static void UpdateMsgReceive(JObject jsonDict)
        {
            Application.Current?.Dispatcher?.Invoke(() =>
            {
                _containerProvider.Resolve<EapViewModel>().DataReceiveFromEap = jsonDict;
            });
        }

        private static void UpdateMsgSend(object data)
        {
            Application.Current?.Dispatcher?.Invoke(() =>
            {
                _containerProvider.Resolve<EapViewModel>().DataSendToEap = data;
            });
        }

        public static async Task<HttpResponseMessage?> RequestDeviceHeartbeatAsync(string methodName)
        {
            var data = new
            {
                machine_code = GlobalValues.MachineCode,
                create_time = DateTimeHelper.GetTimeNowForSql()
            };
            string url = $"{GlobalValues.EapFixedUrl}{methodName}";
            string jsonData = JsonConvert.SerializeObject(data);
            HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            try
            {
                UpdateMsgSend(data);
                var cts = new CancellationTokenSource();
                cts.CancelAfter(_timeOut);
                HttpResponseMessage response = await httpClient.PostAsync(url, content, cts.Token);
                if (response.IsSuccessStatusCode)
                {
                    return response;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                return null;
            }
        }

        public static DataResult ParseNormalResponse(string methodName, HttpResponseMessage? response)
        {
            DataResult dataResult = new DataResult();
            string result = "无响应";
            dataResult.Message = result;
            string rtnCode = "";
            string rtnMsg = "";
            JObject jsonDict = new JObject();
            try
            {
                if (response == null || response.IsSuccessStatusCode == false)
                {
                    if (response == null)
                    {
                        result = "Timeout";
                        dataResult.Message = result;
                    }
                    else
                    {
                        result = response.Content.ReadAsStringAsync().Result;
                    }
                }
                else
                {
                    string responseText = response.Content.ReadAsStringAsync().Result;
                    int responseCode = (int)response.StatusCode;
                    jsonDict = JObject.Parse(responseText);
                    if (responseCode != 200)
                    {
                        result = $"status_code Error: {responseCode}";
                        dataResult.Message = result;
                    }
                    else
                    {
                        result = "OK";
                        rtnCode = jsonDict["status"]?.ToString() ?? "No status Key";
                        rtnMsg = jsonDict["msg"]?.ToString() ?? "No msg Key";
                        dataResult.State = true;
                    }
                }
                return dataResult;
            }
            catch (Exception e)
            {
                result = e.Message;
                dataResult.Message = result;
                return dataResult;
            }
            finally
            {
                UpdateMsgReceive(jsonDict);
                UpdateMsgResponse(result, rtnCode, rtnMsg);
            }
        }



        internal static async Task<HttpResponseMessage?> RequestDeviceAlarmReport(string methodName, string alarmCode, string alarmDes, int alarmLevel, int alarmStaus)
        {
            LogHelper.WriteLogEap($"Send To Eap: methodName:{methodName},alarm_code:{alarmCode},alarm_des:{alarmDes},alarm_level:{alarmLevel},alarm_staus:{alarmStaus}");
            var data = new
            {
                machine_code = GlobalValues.MachineCode,
                alarm_code = alarmCode,
                alarm_des = alarmDes,
                alarm_level = alarmLevel,
                alarm_staus = alarmStaus,
                create_time = DateTimeHelper.GetTimeNowForSql()
            };
            string url = $"{GlobalValues.EapFixedUrl}{methodName}";
            string jsonData = JsonConvert.SerializeObject(data);
            HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            try
            {
                UpdateMsgSend(data);
                var cts = new CancellationTokenSource();
                cts.CancelAfter(_timeOut);
                HttpResponseMessage response = await httpClient.PostAsync(url, content, cts.Token);
                if (response.IsSuccessStatusCode)
                {
                    return response;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                return null;
            }
        }

        internal static async Task<HttpResponseMessage?> RequestDeviceStatusReport(string methodName, int statusCode, string statusName)
        {
            LogHelper.WriteLogEap($"Send To Eap: methodName:{methodName},status_code:{statusCode},status_name:{statusName}");
            var data = new
            {
                machine_code = GlobalValues.MachineCode,
                status_code = $"{statusCode}",
                status_name = statusName,
                create_time = DateTimeHelper.GetTimeNowForSql()
            };
            string url = $"{GlobalValues.EapFixedUrl}{methodName}";
            string jsonData = JsonConvert.SerializeObject(data);
            HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            try
            {
                UpdateMsgSend(data);
                var cts = new CancellationTokenSource();
                cts.CancelAfter(_timeOut);
                HttpResponseMessage response = await httpClient.PostAsync(url, content, cts.Token);
                if (response.IsSuccessStatusCode)
                {
                    return response;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                return null;
            }
        }


        internal static async Task<HttpResponseMessage?> RequestEqpClearFinish(string methodName)
        {
            var data = new
            {
                request_uuid = GetUuid(),
                request_time = DateTimeHelper.GetTimeNowForSql(),
                request_attr = GlobalValues.requestAttr,
                up_sys_name = GlobalValues.upSysName,
                machine_code = GlobalValues.MachineCode,
                func_code = "ClearFinish"
            };
            string url = $"{GlobalValues.EapFixedUrl}{methodName}";
            string jsonData = JsonConvert.SerializeObject(data);
            HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            try
            {
                UpdateMsgSend(data);
                var cts = new CancellationTokenSource();
                cts.CancelAfter(_timeOut);
                HttpResponseMessage response = await httpClient.PostAsync(url, content, cts.Token);
                if (response.IsSuccessStatusCode)
                {
                    return response;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                return null;
            }
        }

        internal static async Task<HttpResponseMessage?> RequestAskDownTaskEvent(string methodName)
        {
            var data = new
            {
                request_uuid = GetUuid(),
                request_time = DateTimeHelper.GetTimeNowForSql(),
                request_attr = GlobalValues.requestAttr,
                up_sys_name = GlobalValues.upSysName,
                line_code = GlobalValues.lineCode,
                machine_code = GlobalValues.MachineCode,
                machine_type = "NA",
                port = "A",
                lot_num = GlobalValues.currentLotId,
                pallet_num = GlobalValues.palletNum
            };
            string url = $"{GlobalValues.EapFixedUrl}{methodName}";
            string jsonData = JsonConvert.SerializeObject(data);
            HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            try
            {
                UpdateMsgSend(data);
                var cts = new CancellationTokenSource();
                cts.CancelAfter(_timeOut);
                HttpResponseMessage response = await httpClient.PostAsync(url, content, cts.Token);
                if (response.IsSuccessStatusCode)
                {
                    return response;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                return null;
            }
        }

        internal static async Task<HttpResponseMessage?> RequestDeviceCraftReportExt(string methodName)
        {
            LogHelper.WriteLogEap($"Send To Eap: methodName:{methodName}");
            var data = new
            {
                machine_code = GlobalValues.MachineCode,
                details = new List<Detail>
                {
                    new Detail
                    {
                        lot_num = GlobalValues.currentLotId!,
                        panel_id = GlobalValues.panelId,
                        item_code = "InSpeed",
                        item_des = "入料传输速度",
                        item_value = GlobalValues.InSpeed.ToString(),
                        uom = "mm/s",
                        is_ok = "1",
                        create_time = DateTimeHelper.GetTimeNowForSql()

                    },
                    new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "OutSpeed",
                            item_des = "出料传输速度",
                            item_value = GlobalValues.OutSpeed.ToString(),
                            uom = "mm/s",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                    new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "DisX",
                            item_des = "靶距X",
                            item_value = GlobalValues.disX. ToString(),
                            uom = "inch",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                      new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "DisY",
                            item_des = "靶距Y",
                            item_value = GlobalValues.disY. ToString(),
                            uom = "inch",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                        new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "DisF",
                            item_des = "方向孔距F",
                            item_value = GlobalValues.disF. ToString(),
                            uom = "inch",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                          new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "DisD",
                            item_des = "前沿距D",
                            item_value = GlobalValues.disD. ToString(),
                            uom = "inch",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                            new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "FirstOffset",
                            item_des = "第一块补偿",
                            item_value = GlobalValues.firstOffset. ToString(),
                            uom = "mm",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                              new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "SecondOffset",
                            item_des = "第二块补偿",
                            item_value = GlobalValues.disY. ToString(),
                            uom = "mm",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                                new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "NGCount",
                            item_des = "Ng总数",
                            item_value = GlobalValues.ngCount. ToString(),
                            uom = "片",
                            is_ok = "0",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                                  new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "OKCount",
                            item_des = "Ok总数",
                            item_value = GlobalValues.okCount. ToString(),
                            uom = "片",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                                    new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "TotalCount",
                            item_des = "总数",
                            item_value = GlobalValues.disY. ToString(),
                            uom = "片",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                                      new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "DyXray01",
                            item_des = "xray01电压",
                            item_value = GlobalValues.dyxray01. ToString(),
                            uom = "KV",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                                        new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "DlXray01",
                            item_des = "xary01电流",
                            item_value = GlobalValues.dlxray01. ToString(),
                            uom = "mA",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                                                             new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "DyXray02",
                            item_des = "xray02电压",
                            item_value = GlobalValues.dyxray02. ToString(),
                            uom = "KV",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },
                                        new Detail
                    {
                            lot_num = GlobalValues.currentLotId!,
                            panel_id = GlobalValues.panelId,
                            item_code = "DlXray02",
                            item_des = "xary02电流",
                            item_value = GlobalValues.dlxray02. ToString(),
                            uom = "mA",
                            is_ok = "1",
                            create_time = DateTimeHelper.GetTimeNowForSql()
                    },

                }
            };
            string url = $"{GlobalValues.EapFixedUrl}{methodName}";
            string jsonData = JsonConvert.SerializeObject(data);
            HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            try
            {
                UpdateMsgSend(data);
                var cts = new CancellationTokenSource();
                cts.CancelAfter(_timeOut);
                HttpResponseMessage response = await httpClient.PostAsync(url, content, cts.Token);
                if (response.IsSuccessStatusCode)
                {
                    return response;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                return null;
            }
        }

        internal static async Task<HttpResponseMessage?> RequestPanelCheckReport(string methodName, bool isOK)
        {
            var data = new
            {
                machine_code = GlobalValues.MachineCode,
                material_code = GlobalValues.currentOrderId,
                lot_num = GlobalValues.currentLotId,
                panel_id = GlobalValues.panelId,
                is_ok = isOK ? 1 : 2,
                create_time = DateTimeHelper.GetTimeNowForDir(),
                defect_list = new List<Detail>
                {
                }
            };
            string url = $"{GlobalValues.EapFixedUrl}{methodName}";
            string jsonData = JsonConvert.SerializeObject(data);
            HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            try
            {
                UpdateMsgSend(data);
                var cts = new CancellationTokenSource();
                cts.CancelAfter(_timeOut);
                HttpResponseMessage response = await httpClient.PostAsync(url, content, cts.Token);
                if (response.IsSuccessStatusCode)
                {
                    return response;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                return null;
            }
        }
    }
}
